package cn.edu.sasu;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.edu.sasu.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.MessageQueue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import cn.edu.sasu.adapter.newsdetail.newsitem.NewsItemAdapter;
import cn.edu.sasu.domain.News;
import cn.edu.sasu.view.NewsListView;
import cn.edu.sasu.view.NewsListView.OnRefreshListener;
import cn.edu.sasu.webservice.SchoolNewsService;
import cn.edu.sasu.webservice.impl.SchoolNewsServiceImpl;

/**
 * 校园新闻（这个相当于一个子的Activity，显示校园新闻的Activity）
 * 
 * @author yubaolinfish
 * 
 */
@SuppressLint("HandlerLeak")
public class NewsSchoolNewsActivity extends Activity {

	/**
	 * 存放新闻的ListView,不过是继承了ListView的自定义的类,在这个MyListView中，增加了可下拉刷新的操作
	 */
	private NewsListView MyListView = null;
	/**
	 * 存放新闻的集合
	 */
	private List<News> list = null;

	private NewsItemAdapter adapter = null;
	private ViewSwitcher viewSwitcher = null;

	private ImageView imageView = null;

	private SchoolNewsService schoolNewsService = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_schoolnews);
		setTheme(android.R.style.Theme_Translucent_NoTitleBar);// 设置这个Activity的主题（没有标题栏）

		schoolNewsService = new SchoolNewsServiceImpl();

		viewSwitcher = (ViewSwitcher) findViewById(R.id.viewswitcher_news_top);

		MyListView = new NewsListView(this);
		MyListView.setCacheColorHint(Color.argb(0, 0, 0, 0));

		imageView = new ImageView(this);
		// imageView = (ImageView) findViewById(R.id.imageView);
		// imageView.setImageResource(R.drawable.temp);

		MyListView.addHeaderView(imageView);

		// 设置刷新按钮的初始图片
		loadMoreButton = new Button(this);

		loadMoreButton.setBackgroundResource(R.drawable.refresh1);
		loadMoreButton.setHint(21 + "");

		// 点击加载更多新闻的时候
		loadMoreButton.setOnClickListener(loadMoreOnClickListener);

		MyListView.addFooterView(loadMoreButton);// 把“加载更多”的按钮放在ListView的末尾
		MyListView.setonRefreshListener(refreshListener);// 注册一个自动刷新的监听器，这个监听器是我们自定义的

		viewSwitcher.addView(MyListView);// 在新闻

		viewSwitcher.addView(getLayoutInflater().inflate(
				R.layout.progress_page, null));// 在加载新闻数据的时候，显示滚动条（滚动的圆圈）
		viewSwitcher.showNext();// 显示下一个，就是滚动条

		MyListView.setOnItemClickListener(listener);// 注册一个监听器，这个监听器是用户点击内容条目的时候，显示具体的内容

		requestRSSFeed();

	}

	/**
	 * 这是一个刷新的图片按钮
	 */
	private Button loadMoreButton = null;

	private int startIndex = 0;
	private int endIndex = 0;

	private OnClickListener loadMoreOnClickListener = new View.OnClickListener() {

		@SuppressWarnings("static-access")
		@Override
		public void onClick(View v) {

			// 设置正在刷新的图片
			// loadMoreButton.setBackgroundResource(R.drawable.refresh2);
			loadMoreButton.setBackgroundResource(R.drawable.refresh2);

			final AnimationDrawable rocketAnimation = (AnimationDrawable) loadMoreButton
					.getBackground();

			// 在Android4.0以前，这个方法是要放在操作主线程的UI中去做的，因为开始的时候，可能背景还没有绑定完成
			getMainLooper().myQueue().addIdleHandler(
					new MessageQueue.IdleHandler() {
						@Override
						public boolean queueIdle() {
							rocketAnimation.start();
							return false;
						}
					});

			startIndex = Integer.parseInt(loadMoreButton.getHint().toString());
			endIndex = startIndex + schoolNewsService.getCOUNT();

			new Thread() {
				@Override
				public void run() {
					list = schoolNewsService
							.getNews(list, startIndex, endIndex);
					handler.sendEmptyMessage(3);
				}
			}.start();
		}
	};

	private OnRefreshListener refreshListener = new OnRefreshListener() {
		@SuppressWarnings("unchecked")
		@Override
		public void onRefresh() {
			new AsyncTask<Map<String, String>, Integer, List<News>>() {

				@Override
				protected List<News> doInBackground(
						Map<String, String>... params) {
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
						e.printStackTrace();
					}
					getData();
					return list;
				}

				@Override
				protected void onPostExecute(List<News> result) {

					loadMoreButton.setHint(21 + "");
					MyListView.setAdapter(new NewsItemAdapter(list,
							NewsSchoolNewsActivity.this));
					MyListView.onRefreshComplete();
				}

			}.execute();
		}
	};

	/**
	 * 开始线程去服务器去数据（异步）
	 */
	private void requestRSSFeed() {
		Thread t = new Thread() {
			@Override
			public void run() {
				super.run();
				try {

					getData();// 获取数据
					if (list.size() == 0) {
						handler.sendEmptyMessage(-1);
					} else {
						handler.sendEmptyMessage(1);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		t.start();
	}

	private Handler handler = new Handler() {
		@SuppressWarnings("static-access")
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case -1:

				break;
			case 1:
				adapter = new NewsItemAdapter(list, NewsSchoolNewsActivity.this);

				MyListView.setOnItemClickListener(listener);
				MyListView.setAdapter(adapter);

				viewSwitcher.showPrevious();

				MyListView.onRefreshComplete();

				// 开始首页的动画 begin
				imageView.setBackgroundResource(R.drawable.main);
				final AnimationDrawable rocketAnimation = (AnimationDrawable) imageView
						.getBackground();

				// 在Android4.0以前，这个方法是要放在操作主线程的UI中去做的，因为开始的时候，可能背景还没有绑定完成
				getMainLooper().myQueue().addIdleHandler(
						new MessageQueue.IdleHandler() {
							@Override
							public boolean queueIdle() {
								rocketAnimation.start();
								return false;
							}
						});

				// 在Android4.0以后，可以直接使用这句话来启动动画
				// rocketAnimation.start();
				// 开始首页的动画 end
				break;
			case 3:

				if (list == null) {

					Toast.makeText(NewsSchoolNewsActivity.this,
							R.string.no_more_news, Toast.LENGTH_SHORT).show();
				} else {
					adapter.notifyDataSetChanged();
					loadMoreButton.setHint(endIndex + "");
					loadMoreButton.setText(getString(R.string.gong)
							+ list.size() + getString(R.string.tiao));
				}
				loadMoreButton.setBackgroundResource(R.drawable.refresh1);

				break;

			default:
				break;
			}
		};
	};

	/**
	 * 用户点击了具体的新闻的监听器，我们就通过Intent集合NewsContentActivity组件
	 */
	private OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if (position == 1) {
				return;
			}
			Intent intent = new Intent(NewsSchoolNewsActivity.this,
					NewsContentActivity.class);
			intent.putExtra("content_url", list.get(position - 2).getNewsId()
					+ "");
			intent.putExtra("count", list.get(position - 2).getCommentsCount()
					+ "");
			NewsSchoolNewsActivity.this
					.startActivityForResult(intent, position);
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		System.out.println(getString(R.string.back));// 用户点击了后退键
		super.onActivityResult(requestCode, resultCode, data);

	}

	/**
	 * 获取数据的方法，并把数据保存到list集合中
	 */
	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.clear();
		params.put("news.startIndex", 1 + "");
		params.put("news.endIndex", 21 + "");
		list = schoolNewsService.postAndParse(params);

	}
}